<?php
require("../../../../../../wp-config.php");
global $wpdb;
header("Content-type: application/octet-stream;charset=UTF-8");
header("Content-Disposition: csv; filename=\"".$wpdb->get_var("SELECT form_name FROM st_ap_forms WHERE form_id=".intval($_GET['id'])).".csv\"");
  function array_to_CSV($data)
    {
		
        $outstream = fopen("php://temp", 'r+');
        fputcsv($outstream, $data, ';', '"');
        rewind($outstream);
        $csv = fgets($outstream);
        fclose($outstream);
        //return chr(255).chr(254).mb_convert_encoding($csv, "UTF-16LE", "UTF-8");
        return $csv;
    }
    foreach($wpdb->get_results("SELECT * FROM st_ap_form_elements WHERE form_id = ".intval($_GET['id'])." AND element_id IN ({$_GET['field']})") as $row){
        $field[] = $row->element_title;
    }
    $csv = array_to_CSV($field);
    foreach($wpdb->get_results("SELECT * FROM st_ap_form_value WHERE form_id = ".intval($_GET['id'])) as $row){
       $json = json_decode($row->json);
       $data = array();
       foreach($field as $fi){
          $data[] = $json->$fi;
       }
       $csv .= array_to_CSV($data);
    }
    $csv = chr(255).chr(254).mb_convert_encoding($csv, "UTF-16LE", "UTF-8");
    echo $csv;
?>
